﻿using System.Diagnostics;
using System.Text;
using WorkTool2.Classes.Data;

namespace WorkTool2.Helpers;

public static class GitHelper
{
    /// <summary>
    /// 执行 Git 命令
    /// </summary>
    /// <param name="command">Git 命令（例如："status"、"pull"、"commit -m 'message'"）</param>
    /// <param name="workingDirectory">Git 仓库目录</param>
    /// <returns>命令执行结果</returns>
    public static (bool IsSuccess, string Message) ExecuteGitCommand(string command, string workingDirectory)
    {
        // 创建进程启动信息
        var startInfo = new ProcessStartInfo()
        {
            FileName = "git", // Git 可执行文件名称
            Arguments = command, // 要执行的 Git 命令
            WorkingDirectory = workingDirectory, // 工作目录（Git 仓库路径）
            RedirectStandardOutput = true, // 重定向标准输出
            RedirectStandardError = true, // 重定向错误输出
            UseShellExecute = false, // 不使用外壳程序
            CreateNoWindow = true, // 不创建窗口
            StandardOutputEncoding = Encoding.UTF8, // 设置编码以支持中文
            StandardErrorEncoding = Encoding.UTF8
        };

        // 执行命令并获取输出
        using var process = new Process { StartInfo = startInfo };
        process.Start();

        // 读取输出和错误信息
        var output = process.StandardOutput.ReadToEnd();
        var error = process.StandardError.ReadToEnd();

        process.WaitForExit();

        // 如果有错误信息，返回错误信息
        if (!string.IsNullOrEmpty(error))
        {
            return (false, $"错误: {error}");
        }

        return (!string.IsNullOrEmpty(output), output);
    }

    /// <summary>
    /// 获取 Git 提交记录
    /// </summary>
    /// <param name="branch">分支名称</param>
    /// <param name="author">作者</param>
    /// <param name="workingDirectory">Git 仓库目录</param>
    /// <param name="startDate">开始时间</param>
    /// <param name="endDate">结束时间</param>
    /// <returns>命令执行结果</returns>
    public static (List<GitCommitRecord> Data, string ErrorMessage) GetGitCommit(string branch, string author, string workingDirectory, string? startDate = null, string? endDate = null)
    {
        var gitCommand = $"log origin/{branch} --author=\"{author}\" --no-merges --pretty=format:\"%h{ToolHelper.SPLIT_STRING}%H{ToolHelper.SPLIT_STRING}%s{ToolHelper.SPLIT_STRING}%cd\" --date=format:\"%Y-%m-%d\"{(startDate == null ? "" : $" --since=\"{startDate}\"")}{(startDate == null ? "" : $" --until=\"{endDate}\"")}";
        var (IsSuccess, Message) = ExecuteGitCommand(gitCommand, workingDirectory);
        if (IsSuccess)
        {
            var branchList = new List<GitCommitRecord>();
            var gitLogResultString = Message;
            var gitResult = gitLogResultString.Split('\n');
            foreach (var line in gitResult)
            {
                var temp = line.Split(ToolHelper.SPLIT_STRING);
                branchList.Add(new GitCommitRecord(temp[0].Trim(), temp[1].Trim(), temp[2].Trim(), temp[3]));
            }
            return (branchList, string.Empty);
        }
        else
        {
            return ([], Message);
        }
    }
}